package com.dy.web.controller.system;

import com.aliyun.sdk.service.dysmsapi20170525.models.QuerySmsTemplateListRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.QuerySmsTemplateListResponse;
import com.aliyun.sdk.service.dysmsapi20170525.models.QuerySmsTemplateListResponseBody;
import com.dy.common.annotation.Log;
import com.dy.common.core.controller.BaseController;
import com.dy.common.core.domain.AjaxResult;
import com.dy.common.core.domain.entity.SysUser;
import com.dy.common.core.page.TableDataInfo;
import com.dy.common.enums.BusinessType;
import com.dy.common.utils.StringUtils;
import com.dy.common.utils.cms.AliyunSmsUtils;
import com.dy.common.utils.poi.ExcelUtil;
import com.dy.system.domain.MobileNote;
import com.dy.system.domain.vo.MobileNoteVo;
import com.dy.system.service.IMobileNoteService;
import com.dy.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.dy.common.utils.cms.AliyunSmsUtils.querySmsTemplateList;

/**
 * 【请填写功能名称】Controller
 *
 * @author anps
 * @date 2022-08-04
 */
@RestController
@RequestMapping("/system/note")
public class MobileNoteController extends BaseController{
    @Autowired
    private IMobileNoteService mobileNoteService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:note:list')")
    @GetMapping("/list")
    public TableDataInfo list(MobileNote mobileNote){
        startPage();
        List<MobileNote> list = mobileNoteService.selectMobileNoteList(mobileNote);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:note:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MobileNote mobileNote){
        List<MobileNote> list = mobileNoteService.selectMobileNoteList(mobileNote);
        ExcelUtil<MobileNote> util = new ExcelUtil<MobileNote>(MobileNote.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:note:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id){
        return AjaxResult.success(mobileNoteService.selectMobileNoteById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:note:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MobileNoteVo mobileNote)throws Exception{
        if (!CollectionUtils.isEmpty(mobileNote.getUserIds())){
            List<Long> userIds = mobileNote.getUserIds();
            List<String> templateCodes = mobileNote.getTemplateCodes();
            if (!CollectionUtils.isEmpty(templateCodes)){
                QuerySmsTemplateListRequest templateListRequest = QuerySmsTemplateListRequest.builder().pageIndex(1).pageSize(20).build();
                QuerySmsTemplateListResponse templateList = querySmsTemplateList(templateListRequest);
                List<QuerySmsTemplateListResponseBody.SmsTemplateList> smsTemplateList = templateList.getBody().getSmsTemplateList();
                for (String templateCode : templateCodes) {
                    for (QuerySmsTemplateListResponseBody.SmsTemplateList list : smsTemplateList) {
                        if (templateCode.equals(list.getTemplateCode())){
                            for (Long userId : userIds) {
                                MobileNote note = new MobileNote();
                                note.setContent(list.getTemplateContent());
                                SysUser sysUser = userService.selectUserById(userId);
                                if (StringUtils.isNotBlank(sysUser.getPhonenumber())){
                                    note.setReceiver(sysUser.getUserName());
                                    note.setUserId(getLoginUser().getUserId());
                                    note.setCreateBy(getLoginUser().getUsername());
                                    note.setStatus("1");
                                    note.setSendUserName(getLoginUser().getUsername());
                                    note.setReceivePhone(sysUser.getPhonenumber());
                                    mobileNoteService.insertMobileNote(note);
                                    AliyunSmsUtils.sendBatchSms(list.getTemplateCode(),sysUser.getPhonenumber(),null);
                                }
                            }
                        }
                    }
                }

            }
        }
        //mobileNoteService.insertMobileNote(mobileNote)
        return toAjax(1);
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:note:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MobileNote mobileNote){
        return toAjax(mobileNoteService.updateMobileNote(mobileNote));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:note:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids){
        return toAjax(mobileNoteService.deleteMobileNoteByIds(ids));
    }
}
